const {exec, escape} = require('../db/mysql');

const user = (username) => {
    username = escape(username);

    const sql = `
        SELECT
        \tbalance,
        \t\`status\`,
        \t\`name\`,
        \trealname
        FROM
        \tt_user,
        \tt_card,
        \tcard_user,
        \tt_role,
        \tuser_role 
        WHERE
        \tusername=${username} 
        \tAND t_user.id = user_role.user_id 
        \tAND user_role.role_id = t_role.id 
        \tAND t_user.id = card_user.user_id 
        \tAND card_user.card_id = t_card.id
    `;

    return exec(sql).then(rows => {
        return rows[0] || {}
    })
};

const diaryAdd = (username, title, content, weather) => {
    username = escape(username);
    title = escape(title);
    content = escape(content);
    weather = escape(weather);

    const sql = `
        select id from t_user where username=${username}
    `;

    return exec(sql).then(rows => {
        const insertDiary = `
            insert into t_diary (user_id,title,content,weather) values (${rows[0].id},${title},${content},${weather})
        `;
        return exec(insertDiary).then(result => {
            return result[0] || {}
        })
    })
};

const diaryManage = (username) => {
    username = escape(username);

    const sql = `
        select t_diary.createtime,title,content,t_diary.id,weather,realname,name from t_user,t_diary,t_role,user_role where username=${username} and t_user.id=t_diary.user_id and t_user.id=user_role.user_id and user_role.role_id = t_role.id
    `;

    return exec(sql).then(rows => {
        return rows || []
    })
};

module.exports = {
    user,
    diaryAdd,
    diaryManage
};